package de.bastian.hinterleitner.tools;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import de.bastian.hinterleitner.database.DataHelper;
import de.hijacksoft.wyc.R;

public abstract class DeleteTask extends AsyncTask<String, String, Boolean>
		implements OnCancelListener {

	private ProgressDialog pd;
	private ArrayList<Entry> entries;
	private WrapperActivity context;
	private boolean show = true;

	public DeleteTask(WrapperActivity c, ArrayList<Entry> entriesToDelete) {
		this(c, entriesToDelete, true);
	}

	public DeleteTask(WrapperActivity c, ArrayList<Entry> entriesToDelete,
			boolean uiThread) {
		show = uiThread;
		context = c;
		entries = entriesToDelete;
	}

	@Override
	protected void onPreExecute() {
		context.setRequestedOrientation(context.getResources()
				.getConfiguration().orientation);
		if (show) {
			pd = new ProgressDialog(context);
			pd.setTitle("");
			pd.setMessage("");
			pd.show();
			pd.setOnCancelListener(this);
		}
	}

	@Override
	protected void onProgressUpdate(String... values) {
		if (values.length >= 1 && show) {
			pd.setMessage(context.getString(R.string.deleting).replace("$1",
					values[0]));
		}
	}

	@Override
	protected Boolean doInBackground(String... params) {
		boolean fail = true;
		DataHelper dh = DataHelper.getDataHelper(context);
		for (int i = 0; i < entries.size(); i++) {
			if (isCancelled()) {
				return true;
			}
			publishProgress(entries.get(i).getName());
			dh.delete(entries.get(i));
		}
		if (params.length >= 1) {
			Category cat = dh.getCategoryByName(params[0]);
			fail = dh.deleteCategory(cat);
		}
		return fail;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (show) {
			pd.dismiss();
		}
		context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		onFinish(result);
	}

	public abstract void onFinish(boolean success);

	@Override
	public void onCancel(DialogInterface arg0) {
		cancel(true);
		if (show) {
			context.dialog(context.getString(R.string.canceldelete));
		}
	}

}